import javax.swing.*;
import java.awt.*;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;

public class GameFrame extends JFrame {
    final int frameSize = 800;
    final int step = 30;
    int delay = 500;
    public static int score =0;
    public  static  int state =0;


    SnakeHead snakeHead = new SnakeHead(GameUtils.rightImg, 30, 570, this);
    List<SnakeBody> snakeBodyList = new ArrayList<>();
    Random random = new Random();
    public FoodObj foodObj = getRandomFood();

    public FoodObj getRandomFood(){
        int lineNum = frameSize / step;
        int x = random.nextInt(lineNum) * step;
        int y = (random.nextInt(lineNum-1)+1) * step;
        return new FoodObj(GameUtils.foodImg,x,y,this);
    }

    public void  launch() {
        this.setVisible(true);
        this.setSize(frameSize,frameSize);
        this.setLocationRelativeTo(null);
        this.setTitle("贪吃蛇");
        this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

        snakeBodyList.add(new SnakeBody(GameUtils.bodyImg,30,570,this));
        snakeBodyList.add(new SnakeBody(GameUtils.bodyImg,0,570,this));

        this.addKeyListener(new KeyAdapter() {
            @Override
            public void keyPressed(KeyEvent e) {
                if(e.getKeyCode() == KeyEvent.VK_SPACE){
                    switch (state) {
                        case 0:
                        case 2:
                            state = 1;break;
                        case 1:
                            state = 2;break;
                        default:break;
                    }
                }
            }
        });
        while (true) {
            if (state == 1) {
            repaint();
            }
            try {
                Thread.sleep(delay);
            }catch (InterruptedException e){
                e.printStackTrace();
            }
        }
    }

    @Override
    public void paint(Graphics graphics){

        graphics.setColor(Color.gray);
        graphics.fillRect(0,0,frameSize,frameSize);
        graphics.setColor(Color.black);
        int lineNum = frameSize / step;
        for (int i =0; i <= lineNum; i++){
            graphics.drawLine(0,i*step,frameSize, i*step);
            graphics.drawLine(i*step,0, i*step, frameSize);
        }
        for (int i = snakeBodyList.size() - 1; i >= 0; i--) {
            snakeBodyList.get(i).paintSelf(graphics);
        }
        snakeHead.paintSelf(graphics);
        foodObj.paintSelf(graphics);
    }

    public static void main(String[] args) {
        GameFrame gameFrame = new GameFrame();
        gameFrame.launch();
    }
}
